/**
* 动弹
*/

'use strict'

import Util from "../common/Util"
import Api from "../common/Api"
import TopTabBar from "../common/TopTabBar"

var moment=require('moment')
var zhCn=require('moment/locale/zh-cn')

var RefreshInfiniteListView = require('../common/RefreshInfiniteListView');
var React =require('react-native');
var {
  View,
  ListView,
  StyleSheet,
  Text,
  SegmentedControlIOS,
  ScrollView,
  Image,
  AsyncStorage,
  AlertIOS,
  TouchableOpacity,
}=React;

var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
export default class Tweet extends React.Component{
  constructor(props){
    super(props)

    this.state={
      values:['最新动弹','热门动弹','我的动弹'],
      selectedValue:'最新动弹',
      tweets:[],
      show:false,
      uid:0,
      pageIndex:1,
      pageSize:20,
    }
  }

  componentDidMount(){
    this._changeSegment(this.state.selectedValue);
  }

  _changeSegment(val){
    this.setState({
      tweets:[],
      show:false,
    })
    this._onRefresh(this.state.selectedValue);
  }

  _onRefresh(val){
    this._loadContent(val,false);
  }

  _reloadMore(val){
    this._loadContent(val,true);
  }

  _loadContent(val,isFooter){
    var that =this;
    var uid=0;
    var url =Api.tweet_list+'?pageSize='+this.state.pageSize;
    if(isFooter){
      this.setState({
        pageIndex:this.state.pageIndex+1,
      })
    }
    url+='&pageIndex='+this.state.pageIndex;
    // this.setState({
    //   tweets:[],
    //   show:false,
    // })
    if(val==='最新动弹'){
      this.setState({
        uid:0,
      })
      that._getContent(url+'&uid='+that.state.uid,isFooter,that);
    }else if(val==='热门动弹'){
      this.setState({
        uid:-1,
      })
      that._getContent(Api.tweet_list+'?uid='+that.state.uid,isFooter,that);
    }else{
      AsyncStorage.getItem('uid')
        .then((uid)=>{
          if(uid){
            that.setState({
              uid:uid,
            })
            that._getContent(url+'&uid='+that.state.uid,isFooter,that);
          }else{
            AlertIOS.alert('登录','请先登录！')
            that.setState({
              show:true,
            })
          }
        })
        .catch((err)=>{
          AlertIOS.alert('出错了','err');
        })
        .done();
    }
  }

  _getContent(url,isFooter,that){
    Util.get(url,(data)=>{
    //  console.log(JSON.stringify(data));
    new Promise(()=>{

      var objs=data.oschina.tweets.tweet;
      if(objs!==undefined){
        var dataList=[];
        if(!Array.isArray(objs)){
          dataList.push(objs);
        }else{
          dataList=objs;
        }
        if(isFooter){
          dataList=that.state.tweets.concat(dataList);
          that.list.hideFooter();
        }else{
          that.list.hideHeader();
        }
        that.setState({
          tweets:dataList,
          show:true,
        })
      }else{
        that.setState({
          show:true,
        })
      }
    });


    })
  }

  _loadPage(id){

  }

  _onInfinite(){

  }

  render(){
    return (
      <View style={styles.container}>
        <TopTabBar
          tabs={this.state.values}
          initTab={0}
          onValueChange={(val,i)=>{
            this.setState({
              selectedValue:val
            });
            this._changeSegment(val);
          }}
          />
        {/*
        <View>
          <SegmentedControlIOS
            tintColor='#4ead7d'
            style={styles.segment}
            selectedIndex={0}
            values={this.state.values}
            onValueChange={(val)=>{
              this.setState({
                selectedValue:val
              });
              this._changeSegment(val);
            }}
            />
        </View>
        */}
        {/*
        <ScrollView>
          {this.state.show ?
          <ListView
            dataSource={ds.cloneWithRows(this.state.tweets)}
            renderRow={(row)=>
              <TweetItem row={row} onPress={this._loadPage.bind(this,row.id)} {...this.props}/>
            }
            />
          :Util.loading
          }
        </ScrollView>
        */}
        <RefreshInfiniteListView
            ref = {(list) => {this.list= list}}
            dataSource={ds.cloneWithRows(this.state.tweets)}
            renderRow={(row)=>
              <TweetItem row={row} onPress={this._loadPage.bind(this,row.id)} {...this.props}/>
            }
            loadedAllData={this._onRefresh.bind(this,this.state.selectedValue)}
            initialListSize={20}
            scrollEventThrottle={10}
            onRefresh = {this._reloadMore.bind(this,this.state.selectedValue)}
            onInfinite = {this._onInfinite}
            >
        </RefreshInfiniteListView>
      </View>
    );
  }
}

class TweetItem extends React.Component{
  constructor(props){
    super(props)
  }

  render(){
    const {row}=this.props;
    const appclient=parseInt(row.appclient);
    var app='';
    if(appclient===2){
      app='手机';
    }else if(appclient===3){
      app='Android';
    }else if(appclient===4){
      app='Iphone';
    }else if(appclient===5){
      app='Window Phone';
    }
    const pubDate=moment(row.pubDate,'YYYY-MM-DD hh:mm:ss').startOf('hour').fromNow();
    return (
      <TouchableOpacity style={styles.item}>
        <View>
          <Image
            Image style={styles.avatar}
            source={row.portrait===''?require('image!default-portrait'):{uri:row.portrait}}
            />
        </View>
        <View style={{flexDirection:'column',flex:1,marginLeft:8,}}>
          <View>
            <Text style={styles.authorText}>{row.author}</Text>
          </View>
          <View style={{marginTop:5}}>
            <Text style={styles.bodyText}>{row.body}</Text>
            {
              row.imgBig!==''?
              <Image
                Image style={styles.imgBig}
                source={{uri:row.imgBig}}
                />
              :<Text></Text>
            }
          </View>
          <View style={{flexDirection:'row',marginTop:8,justifyContent:'space-between'}}>
            <View style={{flexDirection:'row'}}>
              <Text style={styles.footerText}>{pubDate}</Text>
              <Text style={[styles.footerText,{marginLeft:10}]}>{app}</Text>
            </View>
            <View style={{marginRight:10}}>
              <Text style={styles.footerText}>{row.commentCount}</Text>
            </View>
          </View>

        </View>
      </TouchableOpacity>
    )
  }
}

var styles=StyleSheet.create({
  container:{
    backgroundColor:'#eeedf1',
    flex:1,
    marginTop:5,
    flexDirection:'column',
  },
  flex_row:{
    flexDirection:'row',
  },
  segment:{
    backgroundColor:'#f0e9eb',
    marginTop:-5,
  },
  avatar:{
    width:50,
    height:50,
    borderRadius:10,
    borderWidth:Util.pixel,
    borderColor:'#ffffff',
    marginLeft:8
  },
  imgBig:{
    width:100,
    height:100,
    borderRadius:0,
    borderWidth:Util.pixel,
    borderColor:'#ffffff',
    //marginLeft:8
  },
  item:{
    flexDirection:'row',
    flex:1,
    minHeight:80,
    borderBottomWidth:Util.pixel,
    borderColor:'#ccc',
    paddingBottom:3,
    paddingTop:5,
  },
  authorText:{
    color:'#43732e',
    fontWeight:'bold',
    fontSize:13,
  },
  bodyText:{
    fontWeight:'bold',
    fontSize:13,
  },
  footerText:{
    fontWeight:"100",
    color:"gray",
    fontSize:13
  }
});
